package com.gack.netty.util.common;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;

import io.netty.handler.codec.http2.StreamByteDistributor.Writer;

/**
 * 
* @ClassName: ErrorUtil 
* @Description: TODO(异常工具类) 
* @author (ZhangXinYu)  
* @date 2018年9月4日 上午9:07:58 
* @version V1.0
 */
public class ExceptionUtil {

	/**=======================================================================
	 * 获得操作系统中，换行字符串。如Micorsoft Windows XP专业版中换行符"\r\n"
	 * =======================================================================
	 */
	// Note that the line.separator property can be looked up even by applets.
	// 参考org.apache.log4j.Layout
	public final static String LINE_SEP = System.getProperty("line.separator");
	// 参考java.io.BufferedWriter
	@SuppressWarnings("restriction")
	public final static String LINE_SEP2 = (String) java.security.AccessController
			.doPrivileged(new sun.security.action.GetPropertyAction(
					"line.separator"));
 
	/**
	 * @Description:将Throwable对象的错误堆栈内容形成字符串<br> 参考
	 *                                           {@link org.apache.log4j.spi.ThrowableInformation}
	 *                                           代码
	 * @param throwable
	 *            异常对象
	 * @return
	 * @author mahh
	 * @since：2014-9-30 下午02:32:51
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String[] getThrowableStrRep(Throwable throwable) {
		if (throwable == null) {
			return new String[0];
		}
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		throwable.printStackTrace(pw);
		pw.flush();
		LineNumberReader reader = new LineNumberReader(new StringReader(
				sw.toString()));
		ArrayList lines = new ArrayList();
		try {
			String line = reader.readLine();
			while (line != null) {
				lines.add(line);
				line = reader.readLine();
			}
		} catch (IOException ex) {
			lines.add(ex.toString());
		}
		String[] rep = new String[lines.size()];
		lines.toArray(rep);
		return rep;
	}
	
	/**
	 * 获取Exception异常的堆栈信息
	 */
	public static String getExceptionStackTrace(Exception e){
		Writer writer = (Writer) new StringWriter();
        e.printStackTrace(new PrintWriter((java.io.Writer) writer));
        return writer.toString();
	}
	
	/**
	 * 获取Throwable异常的堆栈信息
	 */
	public static String getThrowableExceptionTrace(Throwable throwable){
		Writer writer = (Writer) new StringWriter();
        throwable.printStackTrace(new PrintWriter((java.io.Writer) writer));
        return writer.toString();
	}
	
}
